package cn.jiyun.security;

import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Collection;

public class SuccessHandler  implements AuthenticationSuccessHandler {

    /**
     * 注意:要认证用户成功后才会调用这个方法
     */
    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
        //项目根地址
        String path = request.getContextPath();
        //主机+端口号+项目根路径
        String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";

        UserDetails principal =(UserDetails) authentication.getPrincipal();
        String username = principal.getUsername();
        //通过不同的角色转到不同的页面
        if("admin".equals(username)) {
            response.sendRedirect(basePath+"pages/main.html");
//            response.sendRedirect(basePath+"pages/one.html");
        } else if("test".equals(username)) {
            response.sendRedirect(basePath+"pages/main.html");
//            response.sendRedirect(basePath+"pages/two.html");
        } else {
            System.out.println("其他");
            response.sendRedirect(basePath+"pages/main.html");
        }
    }
}